package com.dx.as.upload;

import android.util.Log;

import com.dx.as.common.CommonUtils;
import com.dx.as.common.ILoadListener;
import com.dx.as.common.JWResult;
import com.dx.as.utils.Utils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import com.dx.as.http.HttpClientHelper;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
 * Created by jwaoo on 2017/7/10.
 */

public class UploadFile {

    private static  Gson gson = new Gson();
    private static Map<Integer,ILoadListener> mapListener = new HashMap<>();
    private static FileOptionSevice service = null;
    private static FileOptionSevice getService(){
        if (service == null) service = HttpClientHelper.getRetrofit().create(FileOptionSevice.class);
        return service;
    }

    public static void uploadFile(final Map<String,Object> map , File file , ILoadListener loadListener){
        uploadFile(map,file,loadListener,null);
    }

    public static void uploadFile(final Map<String,Object> map , File file , ILoadListener loadListener,ProgressRequestBody progressRequestBody) {
        try {
            // create upload service client
            // create RequestBody instance from file


            String type = map.get("media_type").toString();
            map.remove("media_type");
            String end = map.get("end").toString();
            map.remove("end");
            RequestBody requestFile =
                    RequestBody.create(
                            MediaType.parse(type),
                            file
                    );
            // MultipartBody.Part is used to send also the actual file name
            MultipartBody.Part body = null;
            if (progressRequestBody != null){
                body = MultipartBody.Part.createFormData("file",file.getName()+end,progressRequestBody);
            }else {
                body = MultipartBody.Part.createFormData("file", file.getName()+end, requestFile);
            }
            // finally, execute the request
            Call<ResponseBody> call = getService().upload(CommonUtils.getFileUrl(),map,body);
            if (!mapListener.containsKey(call.hashCode())) mapListener.put(call.hashCode(),loadListener);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call,
                                       Response<ResponseBody> response) {
                    if (response != null && response.isSuccessful()){
                        try {
                            if (response != null) {
                                ResponseBody myResponse = response.body();

                                if (myResponse != null){
                                    String body = myResponse.string();
                                    if (!Utils.isEmpty(body)){
                                        JWResult<Map<String,String>> result = gson.fromJson(body,new TypeToken<JWResult<Map<String,String>>>(){}.getType());
                                        mapListener.get(call.hashCode()).onResponse(result.getRst(),0);
                                        mapListener.remove(call.hashCode());
                                    }
                                }
                            }
                        }catch (Exception ex){
                            ex.printStackTrace();
                        }
                    }else{
                        //统一的错误处理
//                        LogUtil.e("Upload error:", t.toString());
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.e("Upload error:", t.toString());
                    mapListener.get(call.hashCode()).onFailure(t);
                    mapListener.remove(call.hashCode());
                }
            });
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

}
